package com.ideal.utils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class HanyuPinyinHelper {

    public static String toHanyuPinyin(String chineseLanguage){
        char[] cl_chars = chineseLanguage.trim().toCharArray();
        StringBuffer hanyupinyin = new StringBuffer();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        // 不带声调
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V) ;
        try {
            for(int i =0;i<cl_chars.length;i++){
                String str = String.valueOf(cl_chars[i]);
                //如果字符是中文，则将中文转为汉语拼音，并且取第一个字母
                if(str.matches("[\u4e00-\u9fa5]+")){
                    hanyupinyin.append(PinyinHelper.toHanyuPinyinStringArray(cl_chars[i],defaultFormat)[0].substring(0,1));
                }else if(str.matches("[0-9]+")){
                    hanyupinyin.append(cl_chars[i]);
                }else if(str.matches("[a-zA-Z]+")){
                    hanyupinyin.append(cl_chars[i]);
                }else{
                    hanyupinyin.append(cl_chars[i]);
                }
            }
        }catch (BadHanyuPinyinOutputFormatCombination e){
            e.printStackTrace();
            System.out.println("字符不能转成汉语拼音");
        }
        return hanyupinyin.toString();
    }

}





































